<template>
  	<div class="app-container">
      	<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="92px">
			<el-form-item label="" prop="user_ids">
				<el-select v-model="queryParams.user_ids" placeholder="请选择社群老师" multiple filterable clearable >
					<el-option v-for="item in teacherList" :key="item.wx_user_id" :label="item.name" :value="item.wx_user_id" />
				</el-select>
			</el-form-item>
			<el-form-item label="" prop="category">
				<el-select v-model="queryParams.category" placeholder="请选择路径" clearable style="width: 160px">
					<el-option v-for="item in categoryList" :key="item.id" :label="item.title" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="" prop="reserve_weight">
				<el-select v-model="queryParams.reserve_weight" placeholder="是否备选老师" clearable style="width: 160px">
					<el-option label="是" value="1" />
					<el-option label="否" value="0" />
				</el-select>
			</el-form-item>
			<el-form-item label="" prop="flow_status">
				<el-select v-model="queryParams.flow_status" placeholder="接量状态" clearable style="width: 160px">
					<el-option label="开启" value="1" />
					<el-option label="暂停" value="0" />
				</el-select>
			</el-form-item>
			<el-form-item label="" prop="message_status">
				<el-select v-model="queryParams.message_status" placeholder="消息通知" clearable style="width: 160px">
					<el-option label="开启" value="1" />
					<el-option label="暂停" value="0" />
				</el-select>
			</el-form-item>
			<el-form-item label="">
				<el-date-picker
					v-model="dateRange"
					type="daterange"
					value-format="yyyy-MM-dd"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					align="right">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
      	</el-form>
		
		<el-row type="flex" class="mb8" justify="space-between" :gutter="10">
			<el-col :span="1.5">
				<el-button plain type="primary" @click="showAdd = true">新增接量老师</el-button>
			</el-col>
        </el-row>
		<el-row type="flex" class="row-bg mb8" justify="space-between" :gutter="10">
			<el-col :span="1.5" v-if="closeEdit">
				<span class="tips">温馨提示：筛选日期包含历史数据，无法进行修改操作</span>
			</el-col>
			<el-col :span="1.5" v-else>
				<span class="mr30">已选择{{mutileRows.length || 0}}个</span>
				<el-button type="primary" @click="openMutile" class="mr30">修改容量</el-button>
				<el-button type="primary" @click="changeTeacher(1)" >开启接量</el-button>
				<el-button type="primary" @click="changeTeacher(0)" class="mr30">暂停接量</el-button>
				<el-button type="primary" @click="changeMsg(1)" >开启消息</el-button>
				<el-button type="primary" @click="changeMsg(0)" class="mr30">暂停消息</el-button>
				<el-tooltip content="当同一个路径，接量老师因为账号异常导致接量状态自动变更为【暂停】时，备选老师接量状态自动变更为【开启】" effect="dark" placement="bottom">
					<el-button type="primary" @click="alternat(1)" >设为备选</el-button>
				</el-tooltip>
				<el-button type="primary" @click="alternat(0)" >取消备选</el-button>
			</el-col>
        </el-row>
		
		<el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="45" align="center" />
			<el-table-column label="路径" align="center" prop="category_title" />
			<el-table-column label="社群老师" align="center" width="120" prop="name" :show-overflow-tooltip="true" />
			<el-table-column label="接量状态" align="center" prop="flow_status" >
				<template slot-scope="scope">
					<span v-if="scope.$index > 0">{{scope.row.flow_status == '1' ? '开启' : '暂停'}}</span>
				</template>
			</el-table-column>
			<el-table-column label="消息通知" align="center" prop="message_status" >
				<template slot-scope="scope">
					<span v-if="scope.$index > 0">{{scope.row.message_status == '1' ? '开启' : '暂停'}}</span>
				</template>
			</el-table-column>

			<el-table-column label="今日设定接量数" align="center" prop="flow_max" >
				<template slot-scope="scope">
					<span>{{ scope.row.sum_flow_max }}</span>
					<el-button type="text" icon="el-icon-edit" :disabled="closeEdit" @click="openSingle(scope.row)" v-if="scope.$index > 0" />
				</template>
			</el-table-column>

			<!-- <el-table-column align="center">
				<template slot="header">
					<el-tooltip content="统计筛选日期下使用获客助手的投放落地页及基木鱼落地页对应老师的报名成功数" effect="dark" placement="bottom">
						<span>已分配<i class="el-icon-question"></i></span>
					</el-tooltip>
				</template>
				<template slot-scope="scope">
					<el-button type="text" @click="goDetail(scope.row,0)">{{scope.row.sum_flow_used}}</el-button>
				</template>
			</el-table-column> -->
			<el-table-column align="center">
				<template slot="header">
					<el-tooltip content="统计筛选日期下使用获客助手的投放落地页及基木鱼落地页对应的加微数据" effect="dark" placement="bottom">
						<span>加微量<i class="el-icon-question"></i></span>
					</el-tooltip>
				</template>
				<template slot-scope="scope">
					<el-button type="text" @click="goDetail(scope.row,1)">{{scope.row.sum_wechat_num}}</el-button>
				</template>
			</el-table-column>
			<el-table-column align="center">
				<template slot="header">
					<el-tooltip content="统计筛选日期下所有企业微信排重数" effect="dark" placement="bottom">
						<span>企微排重<i class="el-icon-question"></i></span>
					</el-tooltip>
				</template>
				<template slot-scope="scope">
					<el-button type="text" @click="goDetail(scope.row,2)">{{scope.row.sum_wechat_unique_num}}</el-button>
				</template>
			</el-table-column>
			<el-table-column label="重复比率" align="center" prop="rate">
				<template slot="header">
					<el-tooltip content="重复比率=1-企微排重数/加微量*100%" effect="dark" placement="bottom">
						<span>重复比率<i class="el-icon-question"></i></span>
					</el-tooltip>
				</template>
				<template slot-scope="scope">
					<span>{{scope.row.rate}}%</span>
				</template>
			</el-table-column>
			<el-table-column label="今日备选" align="center" prop="reserve_weight" >
				<template slot-scope="scope">
					<span v-if="scope.$index > 0">{{scope.row.reserve_weight == '1' ? '是' : '否'}}</span>
				</template>
			</el-table-column>
			<el-table-column label="备注" align="center" prop="reserve_remarks" :show-overflow-tooltip="true" />
		</el-table>

		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="queryParams.page"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

		<el-dialog :title="dialogTitle" :visible.sync="showDialog" width="300px" top="30vh">
			<el-input v-model="flowVal" type="number" placeholder="请输入接量数量"></el-input>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showDialog = false">取 消</el-button>
				<el-button type="primary" @click="submitFlowMax">确 认</el-button>
			</span>
		</el-dialog>

		<el-dialog title="新增接量老师" :visible.sync="showAdd" width="500px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="企业微信名称" prop="name" style="width: 400px;">
					<el-input v-model="form.name" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="企微账户" prop="account" style="width: 400px;">
					<el-input v-model="form.account" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="手机号" prop="mobile" style="width: 400px;">
					<el-input v-model="form.mobile" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="注：">
					<div>新增后老师可登录系统，默认密码123456</div>
					<div>企业微信名称建议和原名称区分</div>
					<div>企微账号可通过企业微信管理后台查看，<span class="light" @click="showImg = true">案例</span></div>
				</el-form-item>
			</el-form>

			<el-dialog width="1300px" title="案例" :visible.sync="showImg" append-to-body>
				<img src="../assets/images/demo.png" alt="">

			</el-dialog>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
  </div>
</template>

<script>
import { getTeacher, getCategory, getList, addUser, updateFlowMax, updateTeacher, updateMessage, updateReserve } from "@/api/teacher";
import { getCurDate } from "@/utils/index"

export default {
  data() {
	return {
		loading: true,	// 遮罩层
		showSearch: true,// 显示搜索条件
		teacherList:[],//社群老师
		categoryList:[],//下拉路径
		productList:[],//下拉产品
		priceList:[],//下拉价格
		dateRange:[],
		queryParams: { 	// 查询参数
			page: 1,
			pageSize: 20,
		},
		closeEdit: false,
		dataList:[],
		total:0,
		dialogTitle:'',	 //接量弹窗标题
		showDialog:false,//接量弹窗开关
		flowVal: '',	 //接量值
		mutileRows:[],	 //接量单值/批量
		showAdd:false,
		form: {},
      	rules: {
        	account: [{ required: true, message: "微信名称不能为空", trigger: "blur" }],
			name: [{ required: true, message: "企微账号不能为空", trigger: "blur" }],
        	mobile: [{ required: true, message: "手机号不能为空", trigger: "blur" }]
		},
		showImg:false
	};
  },
  	created() {
		let date = getCurDate('-')
		this.dateRange = [date,date]
		this.getTeacher()
		this.getCategory()
      	this.getList();
  	},
 	methods: {
		/** 下拉社群老师 */
		getTeacher(){
			getTeacher().then(res => {
				this.teacherList = res.data
			});
		},
		/** 下拉渠道 */
		getCategory(){
			getCategory().then(res => {
				this.categoryList = res.data
			});
		},
		getList() {
			this.loading = true;
			getList(this.queryParams).then(res => {
				let data = res.data.data
				let sum = {
					category_title:'总计',
					sum_flow_max: res.data.statistics.flow_max,
					sum_flow_used: res.data.statistics.flow_used,
					sum_wechat_num: res.data.statistics.wechat_num,
					sum_wechat_unique_num: res.data.statistics.wechat_unique_num
				}
				data.unshift(sum)
				this.dataList = data
				this.dataList.forEach(item => {
					let diff = item.sum_wechat_num - item.sum_wechat_unique_num
					item.rate = item.sum_wechat_num > 0 ? ((diff/item.sum_wechat_num)*100).toFixed(0) : 0
				})
				this.total = res.data.total;
				this.loading = false;
			});
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.page = 1
			let curDate = getCurDate('-')
			//加微时间处理
			if(this.dateRange.length){
				this.dateRange = Array.isArray(this.dateRange) ? this.dateRange : [];
				this.queryParams.start_date = this.dateRange[0];
				this.queryParams.end_date = this.dateRange[1];
				this.closeEdit = curDate == this.dateRange[0] && curDate == this.dateRange[1] ? false : true
			}
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.dateRange = []
			this.payRange = []
			this.orderRange = []
			this.closeEdit = false
			this.handleQuery();
		},
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					this.form.nickname = this.form.name
					addUser(this.form).then(res => {
						this.$modal.msgSuccess("新增成功");
						this.showAdd = false;
					})
				}
			});
		},
		// 取消按钮
		cancel() {
			this.showAdd = false;
			this.resetForm("form");
		},
		handleSelectionChange(rows){
			this.mutileRows = rows
		},
		openSingle(rows){
			this.showDialog = true
			this.mutileRows = [rows]
			this.dialogTitle = ''
		},
		openMutile(){
			if(!this.mutileRows.length){
				this.$modal.msgError("请选择至少一条数据");
				return false
			}
			this.showDialog = true
			this.dialogTitle = '批量修改容量'
		},
		/** 计量批量修改 **/
		submitFlowMax(){
			let numMax = 0,ids = []
			// 最值提取
			if(this.mutileRows.length == 1){
				numMax = this.mutileRows[0].flow_used
			}else{
				let payArr = [],jimuyu = [],mix=[]
				this.mutileRows.forEach(item => {
					item.category == 1 ? payArr.push(item.flow_used) : jimuyu.push(item.wechat_num)
				})
				mix = [Math.max(...payArr),Math.max(...jimuyu)]
				numMax = Math.max(...mix)
			}

			// 拦截数据判断
			if(this.flowVal > 500){
				this.$modal.msgError("最大不超过500接量");
				return false
			}else if(numMax > this.flowVal){
				this.$modal.msgError("修改接量需要大于等于【今日已分配】数量");
				return false
			}
			
			this.mutileRows.forEach(item => {
				ids.push(item.id)
			})
			const params = {
				"flow_max": this.flowVal,
				"ids": ids
			}
			updateFlowMax(params).then(res => {
				this.$modal.msgSuccess("修改成功");
				this.flowVal = ''
				this.queryParams.page = 1
				this.getList()
				this.showDialog = false
			});
		},
		/** 老师状态变更 **/
		changeTeacher(type){
			let names = []
			this.mutileRows.forEach(item => {
				names.push(item.wechat_user_id)
			})
			const params = {
				"wx_user_ids": names,
				"is_not": type
			}
			updateTeacher(params).then(res => {
				let msg = type == 1 ? '开启' : '关闭'
				this.$modal.msgSuccess("接量状态" + msg + "成功");
				this.getList()
			});
		},
		/** 消息状态变更 **/
		changeMsg(type){
			let ids = []
			this.mutileRows.forEach(item => {
				ids.push(item.id)
			})
			const params = {
				"ids": ids,
				"message_status": type
			}
			updateMessage(params).then(res => {
				let msg = type == 1 ? '开启' : '关闭'
				this.$modal.msgSuccess("消息通知已" + msg);
				this.getList()
			});
		},
		/** 备选老师状态变更 **/
		alternat(type){
			let names = [], hasFlow = false, isOpen = false
			
			this.mutileRows.forEach(item => {
				names.push(item.wechat_user_id)
				if(item.flow_status == 1){
					hasFlow = true
				}
				if(item.reserve_weight == 0){
					isOpen = true
				}
			})

			if(type == 1 && hasFlow){
				this.$modal.msgError("仅支持设置接量状态为【暂停】的老师为备选老师，请重新选择");
				return false
			}

			if(type == 0 && isOpen){
				this.$modal.msgError("仅支持备选老师取消备选，请重新选择");
				return false
			}
			const params = {
				"wx_user_ids": names,
				"reserve_weight":  type
			}
			updateReserve(params).then(res => {
				this.$modal.msgSuccess("修改成功");
				this.getList()
			});
		},
		goDetail(rows,type){
			const query = {
				type_id: rows.category,
				is_wechat: type ? 1 : '',
				user: rows.wechat_user_id,
			}
			type > 0 ? query.is_wechat = 1 : query.pay_state = 1
			if(type == 2){
				query.is_repeat = 0
			}
			if(this.closeEdit){
				query.startDate = this.dateRange[0]
				query.endDate = this.dateRange[1]
			}
			this.$router.push({
				path:'index',
				query: query
			})
		}
	}
};
</script>

<style scoped>
	.row-bg{background: #ecf5ff;padding: 10px;}
	.row-bg span{display: inline-block;color: #1890ff;}
	.tips{font-size: 13px;line-height: 36px;}
	.light{color: #1890ff;cursor: pointer;}
	.light:hover{text-decoration: underline;}
</style>